import React, { useEffect, useState, useCallback, useRef } from 'react';
import ReactDOM from 'react-dom';
import { isEmpty } from '@/utils/common';
import useDebounceFn from '@/utils/useDebounceFn';
import Empty from '@/components/Empty/Empty';
import { queryMineCouponList, queryUseCoupon, queryCancleCoupon } from '@/services/coupon';
import { Mask, ModalWrap, AsyncLoading } from '@/design';
import { queryLoveCode } from '@/services/order'
import { useSelector, useDispatch } from 'umi';
import { Scroll } from '@/components/Scroll/Scroll';
import CouponItem from '../../getCoupon/couponItem';
import { Message, Price} from '@/design';

export default function (props: any) {
  const pageNoRef = useRef<number>(1);
  const hasMoreRef = useRef<boolean>(true);
  const { getCouponVisiable, onFresh, btnName, isPayed } = props;
  const [loading, setLoading] = useState<boolean>(false)
  let userInfo = localStorage.getItem('userInfo');
  const { userId = '' } = JSON.parse(userInfo || '{}');
  const [orderlistDt, setOrderlistDt] = useState<any>({
    couponList: [],
    totalSize: 0,
  });

  useEffect(() => {
    if(isPayed || isEmpty(userInfo)) return;
    pageNoRef.current = 1;
    hasMoreRef.current = true;
    fetchAllCoupon(true)
  }, [props.orderNo])

  /** 請求列表 */
  const fetchAllCoupon = async (refresh: boolean) => {
    if (!hasMoreRef.current) return false;
    let result: any;
    let loading = Message.loading({ content: `正在獲取列表…` });
    result = await queryMineCouponList({
      couponStatus: 'usable',
      // pageNo: pageNoRef.current,
      braId: localStorage.getItem('BRAID'),
      userId,
      plateform: 'fnbqrcode',
      orderAmount: props.orderAmount,
      pageSize: 100 //暫時先取100張
    });
    loading.hide();
    if (!result || !result.data) return false;
    pageNoRef.current++;
    setOrderlistDt((prev: any) => {
      let newList = [...(refresh ? [] : prev.couponList), ...result.data.data || []]
      hasMoreRef.current = newList.length < result.data.totalSize
      return {
        couponList: newList,
        totalSize: result.data.totalSize,
      }
    })
  }

  const fetchUseCoupon = async (item:any) => {
    let loading = Message.loading({ content: `訂單更新中…` });
    let result = await queryUseCoupon({
      myCouponId: item.myCouponId,
      orderId: props.orderNo,
      userId: userId
    });
    loading.hide();
    if (!result || !result.data) return false;
    onClose();
    onFresh && onFresh(result.data)
  }

  const getCanUselist = () => {
    let canUseList: any = [];
    orderlistDt.couponList.forEach((elem: any) => {
      if (elem.productUseType === 'specify') {
        let this_amount = 0;
        console.log('orderItemListorderItemList', props.orderItemList);
        (props.orderItemList || []).forEach((item: any) => {
          if (elem.productUseIds && elem.productUseIds.indexOf(item.productId) > -1) {
            this_amount += item.productQuantity * item.productPrice
          }
        });
        if (this_amount > elem.useByAttainAmount) {
          canUseList.push(elem)
        }
      } else {
        canUseList.push(elem)
      }
    });
    return canUseList;
  }

  const fetchCancelCoupon = async() => {
    let loading = Message.loading({ content: `訂單更新中…` });
    let result = await queryCancleCoupon({
      myCouponId: props.myCouponId,
      orderId: props.orderNo,
    });
    loading.hide();
    if (!result || !result.data) return false;
    onClose();
    onFresh && onFresh(result.data)
  }

  const { selectCouponVisiable, onClose, onClickSure, closeText, onLink, myCouponId } = props;
  console.log('getCanUselist', getCanUselist());

  return (<ModalWrap headName={'選擇優惠券'} modalVisiable={selectCouponVisiable} onClose={onClose} onClickSure={onClickSure} btnName={btnName} closeText={closeText} onLink={onLink} leftText={myCouponId ? true : false} onCancel={fetchCancelCoupon}>
     <Scroll hasMore={false} onPullingUp={fetchAllCoupon}>
      {
      !isEmpty(getCanUselist()) && getCanUselist().length > 0 ? getCanUselist().map((item: any, index: number) => {
        return  <CouponItem key={`${item.myCouponId}_${index}`} disabled={item['canUse'] === '0' || item['canUse'] === 0} coupon={item} status={status} couponName canUse onUseCoupon={()=>{fetchUseCoupon(item)}}/>
      } ) : <Empty/>}
    </Scroll>
  </ModalWrap>
  )
}